import * as commonService from '../services/ListReportTable';
import * as common from '../utils/common'
import { Base64 } from 'js-base64'

export default {
    namespace: 'ListReport',
    state: {
        columns: [],
        datas: [],
        total: 0,
        page: 1,
        pageSize: 20,
        sorter: {},
        filters: [],
        controls: [],
        record: {},
        keyColumn: "JLID",
        userIDColumn: "EMID",
        visibleFilterName: null,
        selectedRowKeys: [],
        currRowIndex: null,
        permID: 0,
        divi: {
            visible: false,
            List: [],
        },
        acbl: {
            visible: false,
            sdate: null,
            edate: null,
            list: []
        },
        inrt: {
            visible: false,
            sdate: null,
            edate: null,
            list: []
        }
    },
    reducers: {
        setColumns(state, { payload: { columns, reportName, params, keyColumn, userIDColumn, total } }) {
            let controls = []
            let record = {}
            const count = params.length
            const grid = 1 / parseFloat(count + 2)
            params.map(p => {
                let type = 'text'
                let dataType = 'string'
                if (p.dataType === "number" || p.dataType === "int" || p.dataType === "float") {
                    type = "input-number"
                    dataType = "number"
                } else if (p.dataType === "date") {
                    type = "date"
                    dataType = "date"
                } else if (p.dataType === "month") {
                    type = "month"
                    dataType = "month"
                }
                controls.push({ name: p.name, required: false, type, label: p.caption, grid, dataType, layout: { labelSpan: 7, wrapperSpan: 15 } })
                record[p.name] = p.initVal
            })
            return { ...state, columns, reportName, controls, record, keyColumn, userIDColumn, total };
        },
        save(state, { payload: { params, datas, page, pageSize, sorter, filters, total, record, permID } }) {
            if (!sorter) {
                sorter = {}
            }
            if (!filters) {
                filters = {}
            }
            const visibleFilterName = null
            return { ...state, params, datas, total, page, pageSize, sorter, filters, record, visibleFilterName, permID };
        },
        setVisibleFilterName(state, { payload: { visibleFilterName } }) {
            return { ...state, visibleFilterName };
        },
        setSelectedRowKeys(state, { payload: { selectedRowKeys, currRowIndex } }) {
            return { ...state, selectedRowKeys, currRowIndex };
        },
        saveAcblDivi(state, { payload: { acbl, inrt, divi } }) {
            return { ...state, acbl, inrt, divi };
        },
        hiddenAcblDivi(state, { payload: { } }) {
            const { sdate, edate } = state.acbl
            return {
                ...state, divi: {
                    visible: false,
                    List: [],
                },
                acbl: {
                    visible: false,
                    sdate: sdate,
                    edate: edate,
                    list: []
                },
                inrt: {
                    visible: false,
                    sdate: sdate,
                    edate: edate,
                    list: []
                }
            };
        }
    },
    effects: {
        *fetchRepInfo({ payload: { reportName } }, { call, put }) {
            try {
                const repInfo = yield call(commonService.GetReportColumns, { reportName });
                yield put({
                    type: 'setColumns',
                    payload: {
                        reportName,
                        columns: repInfo.columns,
                        params: repInfo.params,
                        keyColumn: repInfo.keyColumn,
                        userIDColumn: repInfo.userIDColumn,
                        total: repInfo.total,
                    },
                });
            } catch (e) {
                console.log(e)
                throw e
            }
        },
        *fetchData({ payload: { reportName, record, page, pageSize, sorter, filters, permID } }, { select, call, put }) {
            try {
                const mName = 'ListReport_' + reportName
                const m = yield select(state => state[mName]);
                filters = filters === undefined ? m.filters : filters;
                record = record === undefined ? m.record : record;
                page = page === undefined ? m.page : page;
                pageSize = pageSize === undefined ? m.pageSize : pageSize;
                sorter = sorter === undefined ? m.sorter : sorter;
                permID = permID === undefined ? m.permID : permID;
                let whereCauses = common.filtersTowhereCauses(filters)
                const orderItems = common.sorterToOrderItems2(sorter)
                const repReq = {
                    permID: permID,
                    configName: reportName,
                    reportParams: record,
                    whereCauses,
                    orderBY: orderItems,
                    offset: (page - 1) * pageSize,
                    limit: pageSize
                }
                const listData = yield call(commonService.GetReportDataLists, { repReq });
                if (listData) {
                    yield put({
                        type: 'save',
                        payload: {
                            datas: listData.datas,
                            total: listData.total,
                            page: parseInt(page, 10),
                            pageSize: parseInt(pageSize, 10),
                            sorter, filters, record, permID
                        },
                    });
                }
            } catch (e) {
                throw e
            }
        },
        *clearFilter({ payload: { reportName, permID } }, { put }) {
            yield put({ type: 'fetchData', payload: { reportName, permID, filters: {} } });
        },
        *exportData({ payload: { reportName, permID } }, { select, call }) {
            try {
                const mName = 'ListReport_' + reportName
                const m = yield select(state => state[mName]);
                let whereCauses = common.filtersTowhereCauses(m.filters)
                const orderItems = common.sorterToOrderItems2(m.sorter)
                const repReq = {
                    permID: permID,
                    configName: reportName,
                    reportParams: m.record,
                    whereCauses,
                    orderBY: orderItems,
                    offset: -1,
                    limit: -1
                }
                const data = yield call(commonService.ExportReportDatas, { repReq });
                const pname = yield call(commonService.GetPermissionName, { permID });
                if (data) {
                    let a = document.createElement('a');
                    let url = window.URL.createObjectURL(data);
                    let filename = pname + ".xlsx";
                    a.href = url;
                    a.download = filename;
                    document.body.appendChild(a)
                    a.click()
                    setTimeout(function () { document.body.removeChild(a) }, 1000)
                    window.URL.revokeObjectURL(url);
                }
            } catch (e) {
                console.log(e)
                throw e
            }
        },
        *fetchACBL({ payload: { reportName, sdate, edate } }, { select, put, call }) {
            const mName = 'ListReport_' + reportName
            const m = yield select(state => state[mName]);
            let acid = m.selectedRowKeys[0]
            const data = yield call(commonService.GetReportACBL, { reportName, sdate, edate, acid });
            if (data) {
                yield put({
                    type: 'saveAcblDivi',
                    payload: {
                        acbl: {
                            visible: true,
                            sdate: sdate,
                            edate: edate,
                            list: data
                        },
                        inrt: {
                            visible: false,
                            sdate: sdate,
                            edate: edate,
                            list: []
                        },
                        divi: {
                            visible: false,
                            list: [],
                        },
                    },
                });
            }
        },
        *fetchINRT({ payload: { reportName, sdate, edate } }, { select, put, call }) {
            const mName = 'ListReport_' + reportName
            const m = yield select(state => state[mName]);
            let acid = m.selectedRowKeys[0]
            const data = yield call(commonService.GetReportINRT, { reportName, sdate, edate, acid });
            if (data) {
                yield put({
                    type: 'saveAcblDivi',
                    payload: {
                        inrt: {
                            visible: true,
                            sdate: sdate,
                            edate: edate,
                            list: data
                        },
                        acbl: {
                            visible: false,
                            sdate: sdate,
                            edate: edate,
                            list: []
                        },
                        divi: {
                            visible: false,
                            list: [],
                        },
                    },
                });
            }
        },
        *fetchDIVI({ payload: { reportName } }, { select, put, call }) {
            const mName = 'ListReport_' + reportName
            const m = yield select(state => state[mName]);
            const acid = m.selectedRowKeys[0]
            const { sdate, edate } = m.acbl
            const data = yield call(commonService.GetReportDIVI, { reportName, acid });
            if (data) {
                yield put({
                    type: 'saveAcblDivi',
                    payload: {
                        acbl: {
                            visible: false,
                            sdate: sdate,
                            edate: edate,
                            list: []
                        },
                        inrt: {
                            visible: false,
                            sdate: sdate,
                            edate: edate,
                            list: []
                        },
                        divi: {
                            visible: true,
                            list: data,
                        },
                    },
                });
            }
        }
    }
}
